package com.ruoyi.controller;

import com.ruoyi.api.common.R;
import com.ruoyi.domain.*;
import com.ruoyi.dto.*;
import com.ruoyi.platform.annotation.Anonymous;
import com.ruoyi.platform.annotation.Log;
import com.ruoyi.platform.core.controller.BaseController;
import com.ruoyi.platform.core.domain.AjaxResult;
import com.ruoyi.platform.core.domain.entity.SysDictData;
import com.ruoyi.platform.core.domain.entity.SysUser;
import com.ruoyi.platform.core.page.TableDataInfo;
import com.ruoyi.platform.enums.BusinessType;
import com.ruoyi.platform.system.service.ISysUserService;
import com.ruoyi.platform.utils.poi.ExcelUtil;
import com.ruoyi.service.FrontService;
import com.ruoyi.service.IMFileService;
import com.ruoyi.service.ISpaceRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin/front")
@Api(tags = {"前台接口"})
public class FrontController extends BaseController {

    public static final String BANNER_LIST = "bannerList";

    @Autowired
    private FrontService frontService;

    @Autowired
    private IMFileService fileService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISpaceRecordService spaceRecordService;

    @GetMapping(BANNER_LIST)
    @ApiOperation(value = "前台-查询可展示轮播图", httpMethod = "GET", notes = "前台-查询可展示轮播图")
    @Log(title = "前台-查询可展示轮播图", businessType = BusinessType.QUERY)
    public AjaxResult bannerList(@RequestParam("type") Integer type) {
        List<Banner> list = frontService.selectBannerList(type);
        return AjaxResult.success(list);
    }

    @GetMapping("onlineShowList")

    @ApiOperation(value = "前台-查询在线演示", httpMethod = "GET", notes = "前台-查询在线演示")
    @Log(title = "前台-查询在线演示", businessType = BusinessType.QUERY)
    public AjaxResult onlineShowList() {
        return AjaxResult.success(frontService.onlineShowList());
    }

    @GetMapping("sourceCodeList")

    @ApiOperation(value = "前台-查询源码地址", httpMethod = "GET", notes = "前台-查询源码地址")
    @Log(title = "前台-查询源码地址", businessType = BusinessType.QUERY)
    public AjaxResult sourceCodeList() {
        return AjaxResult.success(frontService.sourceCodeList());
    }

    @GetMapping("extendComponentList")
    @ApiOperation(value = "前台-查询组件和系统", httpMethod = "GET", notes = "前台-查询组件和系统")
    @Log(title = "前台-查询组件和系统", businessType = BusinessType.QUERY)
    public AjaxResult extendComponentList(@RequestParam("type") String type) {
        return AjaxResult.success(frontService.extendComponentList(type));
    }

    @GetMapping("documentTreeData")
    @ApiOperation(value = "前台-加载在线文档目录树", httpMethod = "GET", notes = "前台-加载在线文档目录树")
    @Log(title = "前台-加载在线文档目录树", businessType = BusinessType.QUERY)
    public R treeData(@RequestParam("type") Long type) {
        List<CategoryTree> treeList = frontService.documentTreeData(type);
        return R.ok(treeList);
    }

    @GetMapping("selectFileUrl/{id}")

    @ApiOperation(value = "前台-查询文档地址", httpMethod = "GET", notes = "前台-查询文档地址")
    @Log(title = "前台-查询文档地址", businessType = BusinessType.QUERY)
    public AjaxResult selectFileUrl(@PathVariable Integer id) {
        String fileUrl = frontService.selectFileUrl(id);
        return AjaxResult.success("查询成功", fileUrl);
    }

    @GetMapping("firstFile")

    @ApiOperation(value = "前台-在线文档默认显示第一个文档", httpMethod = "GET", notes = "前台-在线文档默认显示第一个文档")
    @Log(title = "前台-在线文档默认显示第一个文档", businessType = BusinessType.QUERY)
    public AjaxResult selectFirstFileId() {
        return AjaxResult.success("查询成功", frontService.selectFirstFile());
    }

    @GetMapping("/selectDocIdByModuleName")
    public AjaxResult selectDocIdByModuleName(String moduleName) {
        return AjaxResult.success("查询成功", frontService.selectDocIdByModuleName(moduleName));
    }

    /**
     * 前台-用户登陆
     */
    @PostMapping("doLogin")
    @ApiOperation(value = "前台-用户登陆", httpMethod = "POST", notes = "前台-用户登陆")
    @Log(title = "前台-用户登陆", businessType = BusinessType.OPERATION)
    public R<String> doLogin(@Validated @RequestBody @ApiParam(name = "前台用户登陆请求体", value = "frontUserLoginDto", required = true) FrontUserLoginDto dto) {
        return R.ok(frontService.doLogin(dto));
    }

    @GetMapping("getSpaceDirectoryTree")
    @ApiOperation(value = "前台-智联空间目录树", httpMethod = "GET", notes = "前台-智联空间目录树")
    @Log(title = "前台-智联空间目录树", businessType = BusinessType.QUERY)
    @Anonymous
    public R getSpaceDirectoryTree() {
        List<SpaceDirectoryTree> treeList = frontService.getSpaceDirectoryTree();
        return R.ok(treeList);
    }


    @GetMapping("getIndexSpaceDirectoryTree")
    @ApiOperation(value = "前台-智联空间目录树", httpMethod = "GET", notes = "前台-智联空间目录树")
    @Log(title = "前台-智联空间目录树", businessType = BusinessType.QUERY)
    @Anonymous
    public R getIndexSpaceDirectoryTree(@RequestParam("type") String type) {
        SysUser user = getLoginUser().getUser();
        List<SpaceDirectory> treeList = frontService.getIndexSpaceDirectoryTree(user.getUserId(), type);
        return R.ok(treeList);
    }

    @GetMapping("getSolutionDirectoryTree")
    @ApiOperation(value = "前台-智联空间解决方案目录树", httpMethod = "GET", notes = "前台-智联空间解决方案目录树")
    @Log(title = "前台-智联空间解决方案目录树", businessType = BusinessType.QUERY)
    @Anonymous
    public R getSolutionDirectoryTree() {
        SysUser user = getLoginUser().getUser();
        List<SpaceDirectory> treeList = frontService.getIndexSpaceDirectoryTree(user.getUserId(), "3");
        return R.ok(treeList);
    }

    @GetMapping("getFirstIndexSpaceDirectoryTree")
    @ApiOperation(value = "前台-智联空间目录树", httpMethod = "GET", notes = "前台-智联空间目录树")
    @Log(title = "前台-智联空间目录树", businessType = BusinessType.QUERY)
    @Anonymous
    public R getFirstIndexSpaceDirectoryTree(@RequestParam(value = "type", required = false) Long type) {
        SysUser user = getLoginUser().getUser();
        List<SpaceDirectory> treeList = frontService.getFirstIndexSpaceDirectoryTree(user.getUserId(), type);
        return R.ok(treeList);
    }

    @GetMapping("getDirectorySelectTree")
    @ApiOperation(value = "前台-智联空间目录树", httpMethod = "GET", notes = "前台-智联空间目录树")
    @Log(title = "前台-智联空间目录树", businessType = BusinessType.QUERY)
    @Anonymous
    public AjaxResult getDirectorySelectTree() {
        return AjaxResult.success("查询成功", frontService.getDirectorySelectTree());
    }

    /**
     * 查看智联文档内容
     */
    @GetMapping("/getSpaceFileUrl/{id}")
    @ApiOperation(value = "前台-查询智联文档地址", httpMethod = "GET", notes = "前台-查询智联文档地址")
    @Log(title = "智联空间文档", businessType = BusinessType.QUERY)
    public AjaxResult getSpaceDocUrl(@PathVariable Long id) {
        return AjaxResult.success("查询成功", frontService.getSpaceDocUrl(id));
    }

    /**
     * 新增智联文件夹
     */
    @PostMapping("/addSpaceDirectory")
    @PreAuthorize("@ss.hasPermi('space:catalogue:addDirectory')")
    @ApiOperation(value = "新增智联空间文件夹", httpMethod = "POST", notes = "新增智联空间文件夹")
    @Log(title = "前台-新增智联空间目录", businessType = BusinessType.INSERT)
    public AjaxResult addSpaceDirectory(@RequestBody SpaceDirectory spaceDirectory) {
        return toAjax(frontService.addSpaceDirectory(spaceDirectory));
    }

    /**
     * 新增智联文档
     */
    @PostMapping("/addSpaceDocument")
    @PreAuthorize("@ss.hasPermi('space:catalogue:addDocument')")
    @ApiOperation(value = "新增智联空间文档", httpMethod = "POST", notes = "新增智联空间文档")
    @Log(title = "智联空间文档", businessType = BusinessType.INSERT)
    public AjaxResult addSpaceDocument(@RequestBody List<SpaceDocument> spaceDocuments) {
        return toAjax(frontService.addSpaceDocument(spaceDocuments));
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", httpMethod = "POST", notes = "上传智联空间文档文件")
    @PreAuthorize("@ss.hasPermi('space:catalogue:upload')")
    @Log(title = "智联空间文档", businessType = BusinessType.INSERT)
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        return AjaxResult.success(frontService.upload(file));
    }

    /**
     * 下载文件
     */
    @PostMapping("downloadFile")
    @PreAuthorize("@ss.hasPermi('space:catalogue:downloadFile')")
    @ApiOperation(value = "下载文件", httpMethod = "GET", notes = "下载智联空间文档文件")
    @Log(title = "智联空间文档", businessType = BusinessType.QUERY)
    public void downloadFile(HttpServletRequest req,
                             HttpServletResponse res,
                             @RequestParam("spaceDocId") Long spaceDocId) {
        frontService.download(req, res, spaceDocId);
    }

    /**
     * 修改智联文件夹
     */
    @PutMapping("/updateSpaceDirectory")
    @PreAuthorize("@ss.hasPermi('space:catalogue:updateDirectory')")
    @ApiOperation(value = "修改智联空间文件夹", httpMethod = "PUT", notes = "修改智联空间文件夹")
    @Log(title = "智联空间文档", businessType = BusinessType.UPDATE)
    public AjaxResult updateSpaceDirectory(@RequestBody SpaceDirectory spaceDirectory) {
        frontService.updateSpaceDirectory(spaceDirectory);
        return AjaxResult.success();
    }

    /**
     * 删除智联文档
     */
    @DeleteMapping("/removeSpaceDocument/{id}")
    @PreAuthorize("@ss.hasPermi('space:catalogue:removeDocument')")
    @ApiOperation(value = "删除智联空间文档", httpMethod = "DELETE", notes = "删除智联空间文档")
    @Log(title = "智联空间文档", businessType = BusinessType.DELETE)
    public AjaxResult removeSpaceDocument(@PathVariable("id") Long id) {
        return toAjax(frontService.removeSpaceDocument(id));
    }

    /**
     * 删除文件夹
     */
    @DeleteMapping("/removeSpaceDirectory/{id}")
    @PreAuthorize("@ss.hasPermi('space:catalogue:removeDirectory')")
    @ApiOperation(value = "删除智联空间文件夹", httpMethod = "DELETE", notes = "删除智联空间文件夹")
    @Log(title = "智联空间文档", businessType = BusinessType.DELETE)
    public AjaxResult removeSpaceDirectory(@PathVariable("id") Long id) {
        return toAjax(frontService.removeSpaceDirectory(id));
    }

    /**
     * 添加到我的收藏
     */
    @PostMapping("/addCollection")
    @PreAuthorize("@ss.hasPermi('space:collection:addCollection')")
    @ApiOperation(value = "添加到我的收藏", httpMethod = "POST", notes = "添加到我的收藏")
    @Log(title = "智联空间文档", businessType = BusinessType.INSERT)
    public AjaxResult addCollection(Long documentId) {
        return toAjax(frontService.addCollection(documentId));
    }

    @PostMapping("/removeCollection")
    @PreAuthorize("@ss.hasPermi('space:mine:removeCollection')")
    @ApiOperation(value = "取消我的收藏", httpMethod = "POST", notes = "取消我的收藏")
    @Log(title = "智联空间文档", businessType = BusinessType.INSERT)
    public AjaxResult removeCollection(Long documentId) {
        return toAjax(frontService.removeCollection(documentId));
    }

    /**
     * 文件类别统计
     */

    @Log(title = "智联空间文档", businessType = BusinessType.QUERY)
    @ApiOperation(value = "文件类别统计", httpMethod = "GET", notes = "文件类别统计")
    @GetMapping("/getStatInfo")
    @PreAuthorize("@ss.hasPermi('space:statics:getStatInfo')")
    public AjaxResult getSpaceDocumentStatInfo() {
        return AjaxResult.success(frontService.getSpaceDocumentStatInfo());
    }

    /**
     * 查询智联文档详细信息
     */

    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询智联文档详细信息", httpMethod = "GET", notes = "查询智联文档详细信息")
    @GetMapping("/getSpaceDocDetail")
    @PreAuthorize("@ss.hasPermi('space:record:getSpaceDocDetail')")
    public AjaxResult getSpaceDocumentDetail(Long spaceDocumentId) {
        SpaceDocumentDetail spaceDocumentDetail = frontService.getSpaceDocumentDetail(spaceDocumentId);
        return AjaxResult.success(spaceDocumentDetail);
    }

    /**
     * 智联空间搜索目录
     */
    @GetMapping("/spaceSearch")
    @PreAuthorize("@ss.hasPermi('space:catalogue:spaceSearch')")
    @ApiOperation(value = "智联空间搜索", httpMethod = "GET", notes = "智联空间搜索")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    public AjaxResult spaceSearch(@RequestParam(value = "searchItem") String searchItem, @RequestParam(value = "type", required = false) Long type) {
        List<SpaceDirectory> spaceDirectories = frontService.fuzzySearchSpaceDoc(searchItem, type);
        return AjaxResult.success(spaceDirectories);
    }

    /**
     * 查询动态列表
     */
    @GetMapping("/getDynamicRecord")
    @PreAuthorize("@ss.hasPermi('space:record:getDynamicRecord')")
    @ApiOperation(value = "查看动态记录", httpMethod = "GET", notes = "查看动态记录")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    public AjaxResult getDynamicRecord(Integer page) {
        List<DynamicRecord> dynamicRecordList = frontService.getSpaceDynamicRecord(page);
        Integer total = frontService.selectAllDynamicRecordCount();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", dynamicRecordList);
        map.put("total", total);
        return AjaxResult.success(map);
    }

    /**
     * 查询文档下载排行榜
     */
    @PreAuthorize("@ss.hasPermi('space:statics:getDownloadRank')")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询文档下载排行榜", httpMethod = "GET", notes = "查询文档下载排行榜")
    @GetMapping("/getDownloadRank")
    public AjaxResult getReadRank(@RequestParam(value = "timeSpan", required = false) String timeSpan, Integer currentPage) {
        int startIndex = (currentPage - 1) * 5;
        List<SpaceRecord> downLoadRankList = frontService.getOperateCountRank(2L, timeSpan, null, null, startIndex);
        List<SpaceRecord> count = frontService.getOperateCountRank(2L, timeSpan, null, null, null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rankList", downLoadRankList);
        map.put("count", count.size());
        return AjaxResult.success(map);
    }

    /**
     * 查询文档阅读排行榜
     */
    @PreAuthorize("@ss.hasPermi('space:statics:getReadRank')")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询文档阅读排行榜", httpMethod = "GET", notes = "查询文档阅读排行榜")
    @GetMapping("/getReadRank")
    public AjaxResult getOperationRank(@RequestParam(value = "timeSpan", required = false) String timeSpan, Integer currentPage) {
        int startIndex = (currentPage - 1) * 5;
        List<SpaceRecord> downLoadRankList = frontService.getOperateCountRank(3L, timeSpan, null, null, startIndex);
        List<SpaceRecord> count = frontService.getOperateCountRank(3L, timeSpan, null, null, null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rankList", downLoadRankList);
        map.put("count", count.size());
        return AjaxResult.success(map);
    }

    /**
     * 查询成员上传排行榜
     */
    @PreAuthorize("@ss.hasPermi('space:statics:getUploadRank')")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询文档上传排行榜", httpMethod = "GET", notes = "查询文档上传排行榜")
    @GetMapping("/getUploadRank")
    public AjaxResult getUploadRank(@RequestParam(value = "timeSpan", required = false) String timeSpan,
                                    @RequestParam(value = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startTime,
                                    @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endTime) {
        return AjaxResult.success(frontService.getUploadRank(1L, timeSpan, startTime, endTime));
    }


    /**
     * 查看我的最近
     */
    @PreAuthorize("@ss.hasPermi('space:mine:getPersonalRecent')")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查看我的最近", httpMethod = "GET", notes = "查看我的最近")
    @GetMapping("/getPersonalRecent")
    public AjaxResult getPersonalRecent(
            @RequestParam(required = false, value = "recordType") String recordType, String documentName, Integer page) {
        SysUser user = getLoginUser().getUser();
        List<PersonalDocInfo> personalDocInfoList = frontService.getRecordByUserId(String.valueOf(user.getUserId()), recordType, documentName, page);
        Integer total = frontService.getTotal(String.valueOf(user.getUserId()), recordType, documentName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", personalDocInfoList);
        map.put("total", total);
        return AjaxResult.success(map);
    }

    /**
     * 查看我的收藏
     */
    @PreAuthorize("@ss.hasPermi('space:mine:getCollection')")
    @Log(title = "智联空间文档操作记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查看我的收藏", httpMethod = "GET", notes = "查看我的收藏")
    @GetMapping("/getCollection")
    public AjaxResult getPersonalCollection(String documentName, Integer page) {
        SysUser user = getLoginUser().getUser();
        List<SpaceCollection> collectionList = frontService.getCollectByUserId(String.valueOf(user.getUserId()), documentName, page);
        Integer total = frontService.getCollectTotal(String.valueOf(user.getUserId()), documentName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", collectionList);
        map.put("total", total);
        return AjaxResult.success(map);
    }

    /**
     * 查看我的收藏
     */
    @Log(title = "成员人数", businessType = BusinessType.QUERY)
    @ApiOperation(value = "成员人数", httpMethod = "GET", notes = "成员人数")
    @GetMapping("/getPersonCount")
    public AjaxResult getPersonCount() {
        return AjaxResult.success(frontService.getPersonCount());
    }

    /**
     * 查看个人资料
     */
    @GetMapping("/getPersonalData")
    @PreAuthorize("@ss.hasPermi('space:mine:getPersonalData')")
    public AjaxResult getPersonalData() {
        Long userId = getLoginUser().getUserId();
        SysUser user = sysUserService.selectUserById(userId);
        return AjaxResult.success(user);
    }

    /**
     * 修改头像
     */
    @PreAuthorize("@ss.hasPermi('space:mine:updatePerAvatar')")
    @PostMapping("/updatePersonalAvatar")
    public AjaxResult updatePersonalAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) throws Exception {
        SysUser user = new SysUser();
        user.setUserId(userId);
        RepFile repFile = fileService.uploadFile(file, "1");
        user.setAvatar(repFile.getFileUrl());
        sysUserService.updateUser(user);
        return AjaxResult.success(user);
    }

    /**
     * 获取智联空间头像
     */
    @GetMapping("/getSpaceAvatar")
    public AjaxResult getSpaceAvatar() {

        SysUser user = sysUserService.selectUserById(1L);
        return AjaxResult.success(user);
    }

    /**
     * 修改智联空间头像
     */
    @PostMapping("/updateSpaceAvatar")
    @PreAuthorize("@ss.hasPermi('space:mine:updateSpaceAvatar')")
    public AjaxResult updateSpaceAvatar(@RequestParam("file") MultipartFile file) throws Exception {
        SysUser user = new SysUser();
        user.setUserId(1L);
        RepFile repFile = fileService.uploadFile(file, "1");
        user.setAvatar(repFile.getFileUrl());
        sysUserService.updateUser(user);
        return AjaxResult.success(user);
    }

    /**
     * 获取文档类型
     */
    @GetMapping("/getDocumentType")
    public AjaxResult getDocumentType() {
        String dictType = "document_type";
        List<SysDictData> list = frontService.selectDocumentType(dictType);
        return AjaxResult.success(list);
    }

    /**
     * 获取文件夹类型
     */
    @GetMapping("/getDirectoryType")
    public AjaxResult getDirectoryType() {
        String dictType = "directory_type";
        List<SysDictData> list = frontService.selectDocumentType(dictType);
        return AjaxResult.success(list);
    }

    /**
     * 回显文件
     */
    @GetMapping("/getEchoDirectory")
    public AjaxResult getEchoDirectory(@RequestParam("id") Long id) {
        SpaceDirectory directory = frontService.selectDirectoryById(id);
        return AjaxResult.success(directory);
    }

    /**
     * 移动文件夹
     */
    @PostMapping("/moveDirectory")
    @PreAuthorize("@ss.hasPermi('space:catalogue:moveDirectory')")
    public AjaxResult moveDirectory(@RequestParam("id") Long id, @RequestParam("parentId") Long parentId, @RequestParam("type") Long type) {
        frontService.moveDirectory(id, parentId, type);

        return AjaxResult.success();
    }


    @GetMapping("/getParentNode")
    public AjaxResult getParentNode(@RequestParam(value = "docId", required = false) Long docId, @RequestParam(value = "directoryId", required = false) Long directoryId) {
        return AjaxResult.success(frontService.getParentDirectoryNode(docId, directoryId));
    }

    @GetMapping("/getDirectoryFirstDoc/{id}")
    public AjaxResult getDirectoryFirstDocId(@PathVariable Long id) {
        return AjaxResult.success(frontService.getDirectoryFirstDocId(id));
    }

    @GetMapping("/getFileTypeWithSuffix")
    public AjaxResult getFileTypeWithSuffix(@RequestParam("fileType") String type) {
        return AjaxResult.success(frontService.getFileTypeWithSuffix(type));
    }

    @GetMapping("/getImagesUnderDirectory")
    public AjaxResult getImagesUnderDirectory(@RequestParam("docId") Long docId) {
        return AjaxResult.success(frontService.getImagesUnderDirectory(docId));
    }

}


